package cn.stylefeng.guns.utils;

import org.apache.commons.lang3.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateUtil {
    private final static SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
    private final static SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");
    private final static SimpleDateFormat sdfDays = new SimpleDateFormat("yyyyMMdd");
    private final static SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private final static SimpleDateFormat sdfTimes = new SimpleDateFormat("yyyyMMddHHmmss");
    private final static SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyyMM");

    private final static SimpleDateFormat sdfHour = new SimpleDateFormat("yyyyMMddHH");

    public final static long MILLISECOND_OF_SECOND = 1000L;

    public final static long MILLISECOND_OF_MINUTE = 60 * MILLISECOND_OF_SECOND;

    public final static long MILLISECOND_OF_HOUR = 60 * MILLISECOND_OF_MINUTE;

    public final static long MILLISECOND_OF_DAY = 24 * MILLISECOND_OF_HOUR;

    public static int getMillisecondsToDays(long milliseconds) {
        return (int) (milliseconds / (((long) 24) * 60 * 60 * 1000));
    }

    public static String humanReadDate(String date) {
        return date.replaceAll("(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2})", "$1年$2月$3日 $4时$5分");
    }

    public static String getDateFormat(Date date) {
        return sdfDay.format(date);
    }

    public static boolean isToday(String date){
        if (isValidDate(date)) {
            try {
                return getDay().equals(sdfDay.format(sdfDay.parse(date)));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static boolean isToday(Date date){
        return getDay().equals(sdfDay.format(date));
    }

    public static boolean isSameday(Date date, Date date2){
        return sdfDay.format(date).equals(sdfDay.format(date2));
    }

    /**
     * 获取YYYY格式
     * @return
     */
    public static String getSdfHour() {
        return sdfHour.format(new Date());
    }

    public static String getMonth() {
        return sdfMonth.format(new Date());
    }

    /**
     * 获取YYYY格式
     * @return
     */
    public static String getSdfTimes() {
        return sdfTimes.format(new Date());
    }

    /**
     * 获取YYYY格式
     * @return
     */
    public static String getYear() {
        return sdfYear.format(new Date());
    }

    /**
     * 获取YYYY-MM-DD格式
     * @return
     */
    public static String getDay() {
        return sdfDay.format(new Date());
    }

    /**
     * 获取YYYYMMDD格式
     * @return
     */
    public static String getDays(){
        return sdfDays.format(new Date());
    }

    /**
     * 获取YYYY-MM-DD HH:mm:ss格式
     * @return
     */
    public static String getTime() {
        return sdfTime.format(new Date());
    }

    /**
     * 获取YYYY-MM-DD HH:mm:ss格式
     * @return
     */
    public static String getTime(Date date) {
        return sdfTime.format(date);
    }

    /**
     * @Title: compareDate
     * @Description: TODO(日期比较，如果s>=e 返回true 否则返回false)
     * @param s
     * @param e
     * @return boolean
     * @throws
     * @author fh
     */
    public static boolean compareDate(String s, String e) {
        if(fomatDate(s)==null||fomatDate(e)==null){
            return false;
        }
        System.out.println(fomatDate(s).getTime()+"=="+fomatDate(e).getTime());
        return fomatDate(s).getTime() >=fomatDate(e).getTime();
    }

    /**
     * @Title: compareDate
     * @Description: TODO(日期时间比较，如果s>=e 返回true 否则返回false)
     * @param s
     * @param e
     * @return boolean
     * @throws
     * @author fh
     */
    public static boolean compareDate2(String s, String e) {
        if(fomatDate2(s)==null||fomatDate2(e)==null){
            return false;
        }
        return fomatDate2(s).getTime() >=fomatDate2(e).getTime();
    }

    /**
     * 格式化日期
     * @return
     */
    public static Date fomatDate(String date) {
        if (StringUtils.isNotBlank(date)) {
            try {
                return sdfDay.parse(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 格式化日期
     * @return
     */
    public static Date fomatDate2(String date) {
        DateFormat fmt = sdfTime;
        try {
            return fmt.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 格式化日期
     * @return
     */
    public static Date fomatDate(String date,String formart) {
        DateFormat fmt = new SimpleDateFormat(formart);
        try {
            return fmt.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 格式化日期
     * @return
     */
    public static Date fomatMayEmptyDate(String date,String formart) {
        if (StringUtils.isNotBlank(date)) {
            DateFormat fmt = new SimpleDateFormat(formart);
            try {
                return fmt.parse(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 校验日期是否合法
     * @return
     */
    public static boolean isValidDate(String s) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        try {
            fmt.parse(s);
            return true;
        } catch (Exception e) {
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            return false;
        }
    }

    /**
     * @param startTime
     * @param endTime
     * @return
     */
    public static int getDiffYear(String startTime,String endTime) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        try {
            //long aa=0;
            int years=(int) (((fmt.parse(endTime).getTime()-fmt.parse(startTime).getTime())/ (1000 * 60 * 60 * 24))/365);
            return years;
        } catch (Exception e) {
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            return 0;
        }
    }
    /**
     * Date转字符串方法
     * @param date
     * @param format 如yyyy-MM-dd HH:mm:ss等
     * @return
     * @throws Exception
     */
    public static String dateToString(Date date,String format) throws Exception{
        if(date==null){
            throw new Exception("dateToString:要转换的日期参数为空！");
        }
        String dateStr = "";
        try{
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            dateStr = sdf.format(date);
        }catch(Exception e){
            e.printStackTrace();
        }

        return dateStr;
    }

    /**
     * <li>功能描述：时间相减得到天数
     * @param beginDateStr
     * @param endDateStr
     * @return
     * long
     * @author Administrator
     */
    public static long getDaySub(String beginDateStr,String endDateStr){
        long day=0;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date beginDate = null;
        Date endDate = null;
        if(StringUtils.isNotEmpty(beginDateStr)&&StringUtils.isNotEmpty(endDateStr)){
            try {
                beginDate = format.parse(beginDateStr);
                endDate= format.parse(endDateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000);
            //System.out.println("相隔的天数="+day);
        }
        return day;
    }

    public static Date getAfterDayTime(int days) {
        return getAfterDayDate(new Date(), days);
    }

    public static String getAfterDayDateStr(int days) {
        return sdfDay.format(getAfterDayTime(days));
    }

    public static String getAfterDayTimeStr(int days) {
        return sdfTime.format(getAfterDayTime(days));
    }

    public static Date getAfterDayTime(Date date, int days) {
        return getAfterDayDate(date, days);
    }

    public static String getAfterDayDateStr(Date date, int days) {
        return sdfDay.format(getAfterDayTime(date, days));
    }

    public static String getAfterDayTimeStr(Date date, int days) {
        return sdfTime.format(getAfterDayTime(date, days));
    }

    public static Date getAfterDayTime(String dateStr, int days) {
        return getAfterDayDate(dateStr, "yyyy-MM-dd", days);
    }

    public static String getAfterDayDateStr(String dateStr, int days) {
        return sdfDay.format(getAfterDayTime(dateStr, days));
    }

    public static String getAfterDayTimeStr(String dateStr, int days) {
        return sdfTime.format(getAfterDayTime(dateStr, days));
    }

    /**
     * 得到n天之后的日期
     * @param date:传入的日期
     * @param days :传入日期N天后所属日期
     * @return
     */
    public static Date getAfterDayDate(Date date, int days) {
        Calendar canlendar = Calendar.getInstance();
        canlendar.setTime(date);
        canlendar.add(Calendar.DATE, days); // 日期减 如果不够减会将月变动
        return canlendar.getTime();
    }

    /**
     * 得到n天之后的日期
     * @param dateStr:传入的日期
     * @param days :传入日期N天后所属日期
     * @return
     */
    private static Date getAfterDayDate(String dateStr, String formart, int days) {
        Calendar canlendar = getCalendar(dateStr, formart);
        canlendar.add(Calendar.DATE, days); // 日期减 如果不够减会将月变动
        return canlendar.getTime();
    }

    /**字符转calendar
     * @param dateStr
     * @param formart
     * @return
     */
    public static Calendar getCalendar(String dateStr, String formart) {
        Calendar calendar = null;
        // 声明一个Date类型的对象
        Date date = null;
        // 声明格式化日期的对象
        SimpleDateFormat format = null;
        if (dateStr != null) {
            // 创建日期的格式化类型
            format = new SimpleDateFormat(formart);
            // 创建一个Calendar类型的对象
            calendar = Calendar.getInstance();
            // forma.parse()方法会抛出异常
            try {
                //解析日期字符串，生成Date对象
                date = format.parse(dateStr);
                // 使用Date对象设置此Calendar对象的时间
                calendar.setTime(date);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return calendar;
    }


    /**
     * 得到n天之后是周几
     * @param days
     * @return
     */
    public static String getAfterDayWeek(String days) {
        int daysInt = Integer.parseInt(days);
        Calendar canlendar = Calendar.getInstance(); // java.util包
        canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
        Date date = canlendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("E");
        String dateStr = sdf.format(date);
        return dateStr;
    }


    /**
     * 日期转星期
     *
     * @param datetime
     * @return
     */
    public static String dateToWeek(String datetime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        Date datet = null;
        try {
            datet = f.parse(datetime);
            cal.setTime(datet);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    /**
     * 日期转星期
     * @param datetime 默认格式"yyyy-MM-dd"
     * @return
     */
    public static String dateToWeek2(String datetime) {
        SimpleDateFormat sdf = new SimpleDateFormat("E");
        String dateStr = sdf.format(fomatDate(datetime));
        return dateStr;
    }

    /**转中文年月日时分秒
     * @param datetime
     * @return
     */
    public static String dateToCn(String datetime) {
        Date ss = fomatDate(datetime);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        String time = format1.format(ss.getTime());
        return time;
    }


    /***
     *  功能描述：日期转换cron表达式
     * @param date
     * @param dateFormat : e.g:yyyy-MM-dd HH:mm:ss
     * @return
     */
    /***
     *
     * @param date 时间
     * @return  cron类型的日期
     */
    public static String getCron(final Date  date){
        SimpleDateFormat sdf = new SimpleDateFormat("ss mm HH dd MM ? yyyy");
        String formatTimeStr = "";
        if (date != null) {
            formatTimeStr = sdf.format(date);
        }
        return formatTimeStr;
    }
    /***
     *
     * @param cron Quartz cron的类型的日期
     * @return  Date日期
     */

    public static Date getDate(final String cron) {


        if(cron == null) {
            return null;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("ss mm HH dd MM ? yyyy");
        Date date = null;
        try {
            date = sdf.parse(cron);
        } catch (ParseException e) {
            return null;// 此处缺少异常处理,自己根据需要添加
        }
        return date;
    }

    /**根据开始时间和结束时间计算分钟
     * @param startTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    public static long getMinute(String startTime,String endTime) throws ParseException{

        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date begin=dfs.parse(startTime);
        Date end = dfs.parse(endTime);
        long between=(end.getTime()-begin.getTime())/1000;//除以1000是为了转换成秒
        long min=between/60;
        return min;
    }

    /**根据毫秒，计算时间
     * @param mss
     * @return
     */
    public static String formatDuring(long mss) {
        long days = mss / (1000 * 60 * 60 * 24);
        long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
        long seconds = (mss % (1000 * 60)) / 1000;
        return days + " 天 " + hours + " 时 " + minutes + " 分 "  + seconds + " 秒 ";
    }


    public static String getTimeDiffStr(String createTime) {
        Calendar before = Calendar.getInstance();
        Calendar after = Calendar.getInstance();
        try {
            before.setTime(sdfTime.parse(createTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long diff = getCalendarDiff(after, before, Calendar.YEAR);
        if (diff > 0) {
            return diff + "年前";
        }
        diff = getCalendarDiff(after, before, Calendar.MONTH);
        if (diff > 0) {
            return diff + "月前";
        }
        diff = getCalendarDiff(after, before, Calendar.DAY_OF_YEAR);
        if (diff > 0) {
            return diff + "天前";
        }
        diff = getCalendarDiff(after, before, Calendar.HOUR_OF_DAY);
        if (diff > 0) {
            return diff + "小时前";
        }
        diff = getCalendarDiff(after, before, Calendar.MINUTE);
        if (diff > 0) {
            return diff + "分钟前";
        }
        diff = getCalendarDiff(after, before, Calendar.SECOND);
        if (diff > 0) {
            return diff + "秒前";
        } else {
            return "现在";
        }
    }

    public static long getSurplusCalendarMillisecondOfDay(Calendar calendar) {
        return MILLISECOND_OF_DAY - getCalendarMillisecondOfDay(calendar);
    }

    public static long getCalendarMillisecondOfDay(Calendar calendar) {
        return (calendar.get(Calendar.HOUR_OF_DAY) * MILLISECOND_OF_HOUR) +
                (calendar.get(Calendar.MINUTE) * MILLISECOND_OF_MINUTE) +
                (calendar.get(Calendar.SECOND) * MILLISECOND_OF_SECOND) +
                (calendar.get(Calendar.MILLISECOND));
    }

    public static long getCalendarDiff(Calendar after, Calendar before, int field) {
        return after.get(field) - before.get(field);
    }

    public static Date getTimeToDateScale(Date time) {
        try {
            return sdfDay.parse(sdfDay.format(time));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 判断当前时间是否在[startTime, endTime]区间，注意时间格式要一致
     *
     * @param nowTime 当前时间
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     * @author lq
     */
    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) throws ParseException {
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdfTime.parse("2019-03-30 23:59:00"));
        System.out.println(getSurplusCalendarMillisecondOfDay(cal));
    }

    public static Date addDay(Date date,int day){
        Calendar   calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE,day); //把日期往后增加一天,整数  往后推,负数往前移动
        date=calendar.getTime(); //这个时间就是日期往后推一天的结果
        return date;
    }

    public static boolean belongCalendar(Date nowTime, String beginTime,
                                         String endTime,boolean addDate){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
        try {
            Date begin = df.parse(dateToString(nowTime,"yyyy-MM-dd")+" "+beginTime);
            Date end = df.parse(dateToString(nowTime,"yyyy-MM-dd")+" "+endTime);
            if(addDate){
                Date centre1 = df.parse(dateToString(nowTime,"yyyy-MM-dd")+" 00:00:00");
                Date centre2 = df.parse(dateToString(addDay(nowTime,1),"yyyy-MM-dd")+" 00:00:00");
                return belongCalendar(nowTime, begin, centre2) || belongCalendar(nowTime, centre1, end);
            }else {
                return belongCalendar(nowTime, begin, end);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断时间是否在时间段内
     *
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime,
                                         Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * 该方法用于比较两个用字符串表示的日期
     * param strDate1,strDate2 要求的格式为'yyyy-mm-dd'
     * 返回值为两个日期相差的天数
     */
    public static int compareDate(Date date1, Date date2) {
        int returnVal = 0;
        try {
            returnVal = (int) ((date2.getTime() - date1.getTime()) / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnVal;
    }

}
